import React, { LegacyRef, useEffect, useRef } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';


interface GMapInter {
  areaData: any;
  area:(data:any)=>void
}
export default function GMap(props: GMapInter) {
  window._AMapSecurityConfig = {
    securityJsCode: 'd28f5e83b4cc1c14996a57a78dfcf109',
  };
  const mapRef = useRef<any>({});
  const inputRef = useRef<HTMLInputElement>({} as HTMLInputElement);
  async function loadMap() {
    const AMap = await AMapLoader.load({
      key: 'e5c7886a9d2653aa5e8730c266feefe2',
      plugins: ['AMap.Geocoder'],
      version: '2.0',
      AMapUI: {
        version: '1.1',
        plugins: ['misc/PositionPicker'],
      },
    });
    mapRef.current.map = new AMap.Map('g-map-container', {
      zoom: 16,
      center: [106.595706, 29.423058],
      //   scrollWheel: false,
    });
    var positionPicker = new AMapUI.PositionPicker({
      mode: 'dragMap',
      map: mapRef.current.map,
      //   iconStyle: {
      //     //自定义外观
      //     url: localIcon,
      //     ancher: [24, 40],
      //     size: [48, 48],
      //   },
    });
    positionPicker.start();
    positionPicker.on('success', (test) => {
      props.area(test)
    });
    mapRef.current.map.on('click', onMapClick);
    mapRef.current.geocoder = new AMap.Geocoder({});
    // mapRef.current.marker = new AMap.Marker();
    // mapRef.current.map.add(mapRef.current.marker);
    // console.log(mapIcon);
  }
  const onMapClick = (value: any) => {
    const { marker } = mapRef.current;
    console.log(value.lnglat);
    marker.setPosition(value.lnglat);
  };
  const onSearch = () => {
    geoCode(inputRef.current.value);
  };
  function geoCode(address: string) {
    const { map, geocoder } = mapRef.current;
    geocoder.getLocation(address, (status: any, result: any) => {
      if (status === 'complete' && result.geocodes.length) {
        const lnglat = result.geocodes[0].location;
        // marker.setPosition(lnglat);
        // map.add(marker);
        // map.setFitView(marker);
        map.panTo(lnglat);
      } else {
        console.error('根据地址查询位置失败');
      }
    });
  }
  useEffect(() => {
    loadMap();
  }, [props.areaData]);
  // useEffect(() => {
    // if (props.areaData) {
    //   geoCode(props.areaData);
    // }
  // }, [props.areaData]);
  return (
    <>
      <div id="g-map-container" style={{ height: '100%' }}></div>
    </>
  );
}
